<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <el-card style="border-radius: 10px">
        <div class="head-container">
          <el-input
            v-model="itemTypeName"
            placeholder="请输入分类名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="itemTypeOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
        </el-card>
      </el-col>
      <el-col :span="20" :xs="24">
      <el-card style="border-radius: 10px">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="产品物料编码" prop="itemCode">
          <el-input
            v-model="queryParams.itemCode"
            placeholder="请输入产品物料编码"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="产品物料名称" prop="itemName">
          <el-input
            v-model="queryParams.itemName"
            placeholder="请输入产品物料名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      </el-card>
        <div style="height: 15px"></div>
      <el-card style="border-radius: 10px">
      <el-row :gutter="10" class="mb8">
<!--        <el-col :span="1.5" v-if="this.isShowCount <= 0">
          <el-button
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
          >导入</el-button>
        </el-col>-->
        <el-col :span="1.5">
          <el-button
            type="warning"
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['mes:wm:wmstock:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="wmstockList" @selection-change="handleSelectionChange" border show-summary :summary-method="getTotalSummaries">
        <el-table-column label="序号" type="index" width="50"/>
        <el-table-column label="产品物料编码" align="center" prop="itemCode" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleDetail(scope.row)"
            >{{scope.row.itemCode}}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="产品物料名称" align="center" prop="itemName" :show-overflow-tooltip="true"/>
        <el-table-column label="规格型号" align="center" prop="specification" :show-overflow-tooltip="true"/>
        <el-table-column label="单位" align="center" prop="unitOfMeasure" />
        <el-table-column label="在库数量"  align="center" prop="quantityOnhand">
          <template slot-scope="scope">
            <el-tag type="primary">{{ scope.row.quantityOnhand }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center" prop="price" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.price.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="总金额" align="center" prop="totalAmount" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.totalAmount.toFixed(2) | formatMoney }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-for="col in columnsConfig"
          :key="col.prop"
          :label="col.label"
          :prop="col.prop"
          :width="col.width"
          :align="col.align"
          v-if="col.show">
        </el-table-column>
<!--        <el-table-column label="入库批次号" width="100px" align="center" prop="batchCode" :show-overflow-tooltip="true"/>
        <el-table-column label="仓库" align="center" prop="warehouseName" :show-overflow-tooltip="true"/>
        <el-table-column label="库区" align="center" prop="locationName" :show-overflow-tooltip="true"/>
        <el-table-column label="库位" align="center" prop="areaName" :show-overflow-tooltip="true"/>
        <el-table-column label="供应商编号" width="100px" align="center" prop="vendorCode" />
        <el-table-column label="供应商名称" width="120px" align="center" prop="vendorName" :show-overflow-tooltip="true"/>
&lt;!&ndash;        <el-table-column label="供应商简称" width="100px" align="center" prop="vendorNick" />&ndash;&gt;
        <el-table-column label="生产工单" width="100px" prop="workorderCode" :show-overflow-tooltip="true"/>
        <el-table-column label="入库日期" align="center" prop="recptDate" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.recptDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="库存有效期" align="center" prop="expireDate" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.expireDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>-->
        <el-table-column label="操作" align="center"  width="180px">
          <template slot-scope="scope">
            <el-tooltip content="详情" placement="top">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-view"
                @click="handleDetail(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>

      </el-table>

<!--      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />-->
        <div class="pagination-container">
          <div class="pagination-summary">
            <span >总数量：{{ tatalAllQuantity}}</span>
            <span style="margin-left: 10px;">总金额：{{totalAllAmount | formatMoney  }}</span>
          </div>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </el-card>
      </el-col>
    </el-row>
    <el-dialog title="库存详情" v-if="showDetail" :visible.sync="showDetail" :modal= false width="80%"  append-to-bod>
      <el-card style="border-radius: 10px">
      <el-table v-loading="processLoading" :data="detailList"   show-summary :summary-method="getSummaries" border>
        <el-table-column label="序号" type="index" width="50"/>

        <el-table-column label="产品物料编码" width="120px" align="center" prop="itemCode" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="产品物料名称" width="150px" align="center" prop="itemName" :show-overflow-tooltip="true"/>
        <el-table-column label="规格型号" align="center" prop="specification" :show-overflow-tooltip="true"/>

        <el-table-column label="单位" align="center" prop="unitOfMeasure" />
        <el-table-column label="入库批次号" width="100px" align="center" prop="batchCode" :show-overflow-tooltip="true"/>
        <el-table-column label="仓库" align="center" prop="warehouseName" :show-overflow-tooltip="true"/>
        <el-table-column label="库区" align="center" prop="locationName" :show-overflow-tooltip="true"/>
        <el-table-column label="库位" align="center" prop="areaName" :show-overflow-tooltip="true"/>
        <el-table-column label="在库数量" width="100" align="center" prop="quantityOnhand">
          <template slot-scope="scope">
            <el-tag type="primary">{{ scope.row.quantityOnhand }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="供应商编号" width="100px" align="center" prop="vendorCode" />
        <el-table-column label="供应商名称" width="120px" align="center" prop="vendorName" :show-overflow-tooltip="true"/>
        <!--        <el-table-column label="供应商简称" width="100px" align="center" prop="vendorNick" />-->
        <el-table-column label="生产工单" width="100px" prop="workorderCode" :show-overflow-tooltip="true"/>
        <el-table-column label="入库日期" align="center" prop="recptDate" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.recptDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="库存有效期" align="center" prop="expireDate" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.expireDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center" prop="price" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column label="金额" align="center" prop="amount" width="120">
          <template slot-scope="scope">
            <span>{{(scope.row.price * scope.row.quantityOnhand) | formatMoney }}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="detailtotal>0"
        :total="detailtotal"
        :page.sync="detailQueryParams.pageNum"
        :limit.sync="detailQueryParams.pageSize"
        @pagination="getDetailList"
      />
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getAllTotal, getTotalList, listWmstock} from "@/api/mes/wm/wmstock";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/mes/md/itemtype";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getColumnsConfigKey} from "@/api/system/columnsconfig";


export default {
  name: "Wmstock",
  components: { Treeselect },
  data() {
    return {
      columnsConfig:[],
      totalAllAmount:0,
      tatalAllQuantity:0,
      isShowCount:1,
      showDetail:false,
      processLoading:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      itemTypeName: null,
      // 总条数
      total: 0,
      //物料产品分类树
      itemTypeOptions: undefined,
      // 库存记录表格数据
      wmstockList: [],
      detailList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/mes/wm/wmstock/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemTypeId: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        batchCode: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        areaId: null,
        areaCode: null,
        areaName: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        vendorNick: null,
        quantityOnhand: null,
        workorderCode: null,
        expireDate: null,
        xbkCode: 'XBK_VIRTUAL'
      },
      detailtotal:0,
      detailQueryParams: {
        pageNum: 1,
        pageSize: 10,
        itemTypeId: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        batchCode: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        areaId: null,
        areaCode: null,
        areaName: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        vendorNick: null,
        quantityOnhand: null,
        xbkCode: 'XBK_VIRTUAL'
      },
      // 表单参数
      form: {},
    };
  },
  watch: {
    // 根据名称筛选分类树
    itemTypeName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getTreeselect();
    this.getItemBase()
  },
  methods: {
    /** 查询库存记录列表 */
    getList() {
      this.tatalAllQuantity=0
      this.totalAllAmount=0
      this.loading = true;
      getTotalList(this.queryParams).then(response => {
        this.wmstockList = response.rows;
        this.total = response.total;

        getAllTotal(this.queryParams).then(response=>{
          this.tatalAllQuantity=response.data.quantityOnhand
          this.totalAllAmount=response.data.totalAmount
        })
        this.loading = false;
    /*    if(null == this.queryParams.itemTypeId){
          this.isShowCount = this.wmstockList.length
        }else {
          this.isShowCount = 1
        }*/
      });

    },
    getItemBase(){
      getColumnsConfigKey('MdItem_Base').then(res=>{
        this.columnsConfig = JSON.parse(res.data);
      })
    },
  getTotalSummaries(param) {
      const { columns, data } = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }

        if (column.label === '在库数量') {
          const total = data.reduce((sum, row) => sum + row.quantityOnhand, 0);
          sums[index] = total; // 可以改成 `total.toString()` 如果需要字符串
        }
        else if (column.label === '总金额') {
          const total = data.reduce((sum, row) => {
            return sum + (row.price * row.quantityOnhand);
          }, 0);
          sums[index] = this.$options.filters.formatMoney(total);
        }
        else {
          // 其他列不合并 都是'—' 不好看，就直接空着
          // sums[index] = '—';
          sums[index] = '';
        }
      });

      return sums;
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }

        if (column.label === '在库数量') {
          const total = data.reduce((sum, row) => sum + row.quantityOnhand, 0);
          sums[index] = total; // 可以改成 `total.toString()` 如果需要字符串
        }
        else if (column.label === '金额') {
          const total = data.reduce((sum, row) => {
            return sum + (row.price * row.quantityOnhand);
          }, 0);
          sums[index] = this.$options.filters.formatMoney(total);
        }
        else {
          // 其他列不合并 都是'—' 不好看，就直接空着
          // sums[index] = '—';
          sums[index] = '';
        }
      });

      return sums;
    },

    /** 查询分类下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.itemTypeOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.showDetail = false;
      this.getList()
    },
    // 查看按钮操作
    handleDetail(row) {
      this.showDetail = true;
      this.processLoading = true;
      this.detailQueryParams.itemId=row.itemId
      this.getDetailList()
    },
    getDetailList(){
      listWmstock(this.detailQueryParams).then(response => {
        this.detailList = response.rows;
        this.detailtotal = response.total;
        this.processLoading = false;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.itemTypeId = data.id;
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.materialStockId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/wm/wmstock/exportZongLiang', {
        ...this.queryParams
      }, `wmstock_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "库存数据导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('mes/wm/wmstock/importTemplate', {
      }, `wmstock_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
  ,
  filters: {
    formatMoney(value) {
      if (isNaN(value)) return '0.00';
      return Number(value)
        .toFixed(2)
        .replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    },
  }
};
</script>
<style scoped>
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
}

.pagination-summary {
  font-size: 14px;
  color: #606266;
}
</style>
